package com.crm.system.controller.customerManager;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.framework.listener.ExcelListener;
import com.crm.model.dto.CustomerDTO;
import com.crm.model.qo.sys.ImportFailureLogQO;
import com.crm.model.vo.customerManager.CustomerImportNewVO;
import com.crm.model.vo.customerManager.UserCustomerImportVO;
import com.crm.model.vo.sys.ImportFailureLogVO;
import com.crm.system.service.customerManager.CustomerImportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @ Author ：pym
 * @ Date   ：2021/2/23 10:33
 */
@RestController
@RequestMapping("/customerImport")
@Slf4j
public class CustomerImportController {
    @Autowired
    CustomerImportService customerImportService;

    /**
     * 下载客户导入模板
     * @param response
     */
    @GetMapping("/downloadCustomerTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        /*InputStream fis = null;
        OutputStream os = null;
        String path = "";
        try {
            String fileName="customer.xlsx";
            //根据系统来判断取相对路径还是绝对路径
            String osName = System.getProperty("os.name");
            if (osName.toLowerCase().startsWith("win")) {
                path = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"static/excelTemplate/customer.xlsx";
            } else {
                path = "/root/system/excelTemplate/customer.xlsx";
            }

            fileName = new java.net.URLDecoder().decode(fileName, "utf-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso8859-1"));
            //以流的形式下载文件
            fis = new BufferedInputStream(new FileInputStream(path));
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fis);
            os = new BufferedOutputStream(response.getOutputStream());
            xssfWorkbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("CustomerImportController downloadCustomerTemplate error:", e);
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e1) {
                    log.error("CustomerImportController downloadCustomerTemplate InputStream close error:", e1);
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e2) {
                    log.error("CustomerImportController downloadCustomerTemplate OutputStream close error:", e2);
                }
            }
        }*/

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("客户导入模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            List<CustomerDTO> customerDTOList = new ArrayList<CustomerDTO>();
            customerDTOList.add(new CustomerDTO("大成1", "在业", "11", "100", new SimpleDateFormat("yyyy-MM-dd").parse("2021-1-19"), new SimpleDateFormat("yyyy-MM-dd").parse("2021-1-26"), "北京", "北京市", "东城区", "15311111111", "59088666", "111@qq.com", "333@qq.com", "91370783165684156E","91370783165684156E", "370783018084156", "16568415-6", "36", "集体所有制", "建筑业", "555", "www.111.com", "32233", "333","sadas"));
            customerDTOList.add(new CustomerDTO("大成2", "在业", "22", "200", new SimpleDateFormat("yyyy-MM-dd").parse("2021-1-20"), new SimpleDateFormat("yyyy-MM-dd").parse("2021-1-27"), "北京", "北京市", "西城区", "15322222222", "59088777", "222@qq.com", "555@qq.com", "91370304164280854G","91370304164280854G", "370304018011577", "16428085-4", "7", "股份合作制", "房屋建筑业", "666", "www.222.com", "12213", "222","asdasd"));
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), CustomerDTO.class).autoCloseStream(Boolean.FALSE).sheet("客户导入模板")
                    .doWrite(customerDTOList);
        } catch (Exception e) {
            log.error("CustomerImportController downloadCustomerTemplate : ", e);
        }
    }

    /**
     * 客户导入功能
     * @param request
     * @param file 导入文件
     * @param customerPoolId 客户池ID
     * @return
     * @throws IOException
     */
    @PostMapping("/customerImport")
    public DataResponse customerImport(HttpServletRequest request,
                                   @RequestParam MultipartFile file,
                                   @RequestParam String customerPoolId) {
        try {
            ExcelListener excelDataListener = new ExcelListener();
            List<CustomerImportNewVO> list = EasyExcel.read(file.getInputStream(), CustomerImportNewVO.class,excelDataListener).sheet(0).doReadSync();
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }
            JSONObject jsonObject = customerImportService.importCustomer(list,customerPoolId);
            //客户池容量是否已超
            Boolean ifMoreCustomerCapacity = jsonObject.getBoolean("moreCustomerCapacity");
            if(ifMoreCustomerCapacity){
                return new DhResponse(ResponseCodeEnum.IMPORT_CUSTOMER_EXCEEDS_CAPACITY.getResponseCode());
            }
            //返回导入数量、重复数量
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),jsonObject);
        } catch (Exception e) {
            log.error("CustomerImportController customerImport error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 用户端客户导入
     * @Author pym
     * @Date  2021/5/18 16:37
     * @param request
     * @param file 导入文件
     * @param customerPoolId 客户池ID
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @PostMapping("/userCustomerImport")
    public DataResponse userCustomerImport(HttpServletRequest request,
                                       @RequestParam MultipartFile file,
                                       @RequestParam String customerPoolId) {
        try {
            ExcelListener excelDataListener = new ExcelListener();
            List<UserCustomerImportVO> list = EasyExcel.read(file.getInputStream(), UserCustomerImportVO.class,excelDataListener).sheet(0).doReadSync();
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }
            JSONObject jsonObject = customerImportService.importUserCustomer(list,customerPoolId);
            //客户池容量是否已超
            Boolean ifMoreCustomerCapacity = jsonObject.getBoolean("moreCustomerCapacity");
            if(ifMoreCustomerCapacity){
                return new DhResponse(ResponseCodeEnum.IMPORT_CUSTOMER_EXCEEDS_CAPACITY.getResponseCode());
            }
            //返回导入数量、重复数量
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),jsonObject);
        } catch (Exception e) {
            log.error("CustomerImportController customerImport error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 客户冲突数据列表
     * @Author pym
     * @Date  2021/5/28 10:45
     * @param request
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @param importFailureLogQO -查询条件
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @PostMapping("/customerConflictList")
    public DataResponse customerConflictList(HttpServletRequest request,
                                             @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                             @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                             @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                             @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                             ImportFailureLogQO importFailureLogQO//查询条件
    ){
        try{
            DhPageInfo<ImportFailureLogVO> customerConflictList
                    = customerImportService.selectCustomerConflictList(pageIndex,pageSize,importFailureLogQO,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerConflictList);
        }catch(Exception e){
            log.error("customerImport customerConflictList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 导入失败数据列表
     * @Author pym
     * @Date  2021/5/28 14:20
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @param importFailureLogQO -查询条件
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @PostMapping("/importFailedDataList")
    public DataResponse importFailedDataList(HttpServletRequest request,
                                             @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                             @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                             @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                             @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                             ImportFailureLogQO importFailureLogQO//查询条件
    ){
        try{
            DhPageInfo<ImportFailureLogVO> importFailedDataList
                    = customerImportService.selectImportFailedDataList(pageIndex,pageSize,importFailureLogQO,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),importFailedDataList);
        }catch(Exception e){
            log.error("customerImport importFailedDataList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 导入客户原始数据
     * @Author pym
     * @Date  2021/7/13 11:40
     * @param request
     * @param file 导入文件
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @PostMapping("/customerRawDataImport")
    public DataResponse customerRawDataImport(HttpServletRequest request,
                                           @RequestParam MultipartFile file) {
        try {
            ExcelListener excelDataListener = new ExcelListener();
            List<UserCustomerImportVO> list = EasyExcel.read(file.getInputStream(), UserCustomerImportVO.class,excelDataListener).sheet(0).doReadSync();
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }
            JSONObject jsonObject = customerImportService.importCustomerRawData(list);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),jsonObject);
        } catch (Exception e) {
            log.error("CustomerImportController customerRawDataImport error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

}
